<script setup lang="ts">
  import TableSearch from '@/components/common/TableSearch.vue'
  import { reactive, ref, computed } from 'vue'
  import { page, remove, save, update } from '@/api/tag.ts'
  import { Tag, TagPageParam, TagSaveParam } from '@/types'
  import { FormOption, TableColumns } from '@/types/form-option.ts'
  import TableCustom from '@/components/common/TableCustom.vue'
  import TableEdit from '@/components/common/TableEdit.vue'
  import { ElMessage } from 'element-plus'
  import { CirclePlusFilled } from '@element-plus/icons-vue'
  import { normalizeColor } from '@/utils/color-util'
  import { iconCategories, colorPresets } from '@/config/icon-presets'

  const {
    columns,
    tableData,
    total,
    param,
    getData,
    handleDelete,
    handleAdd,
    handleEdit,
    handleSearch,
    changePage,
    searchOpt,
  } = useTableCustom()
  const { visible, isEdit, rowData, editColumns, closeDialog, updateData } = useDialog()

  getData()

  //表格配置
  function useTableCustom() {
    //搜索配置
    const searchOpt = ref<FormOption[]>([{ type: 'input', label: '名字：', prop: 'name' }])
    // 查询参数
    const param = reactive<TagPageParam>({
      name: '',
      pageNum: 1,
      pageSize: 10,
    })

    // 表格字段配置
    const columns = ref<TableColumns[]>([
      { type: 'index', prop: '', label: '序号', width: 55, align: 'center' },
      { prop: 'icon', label: '图标', width: 80, align: 'center' },
      { prop: 'name', label: '名字', align: 'left' },
      { prop: 'color', label: '颜色', width: 120, align: 'center' },
      {
        prop: 'blogs',
        label: '博客数量',
        width: 100,
        align: 'center',
        formatter: (item: unknown) => (Array.isArray(item) ? item.length : 0),
      },
      { prop: 'operator', label: '操作', width: 250, viewHidden: true, editHidden: true },
    ])
    //表格数据
    const tableData = ref<Tag[]>([])
    //总数
    const total = ref(0)
    //跳转页码
    const changePage = (val: number) => {
      param.pageNum = val
      getData()
    }
    // 删除相关
    const handleDelete = async (row: Tag) => {
      await remove({ id: row.id })
      ElMessage.success('删除成功')
      await getData()
    }
    //查询分页
    const getData = async () => {
      const data = await page(param)
      tableData.value = data.records
      total.value = data.total
    }

    //搜索方法
    const handleSearch = () => {
      changePage(1)
    }

    const handleAdd = () => {
      rowData.value = {}
      visible.value = true
      isEdit.value = false
    }

    const handleEdit = (row: Tag) => {
      visible.value = true
      isEdit.value = true
      rowData.value = row
    }

    return {
      columns,
      tableData,
      total,
      param,
      getData,
      handleDelete,
      handleAdd,
      handleEdit,
      handleSearch,
      changePage,
      searchOpt,
    }
  }

  function useDialog() {
    const visible = ref(false)
    const isEdit = ref(false)
    const rowData = ref()

    // 图标和颜色预设值现在从配置文件导入

    // 根据是否为编辑模式动态生成表单配置
    const editColumns = computed<FormOption[]>(() => {
      if (isEdit.value) {
        // 编辑模式：只能修改颜色和图标
        return [
          { type: 'input', prop: 'name', label: '标签名字', disabled: true, span: 12 },
          { type: 'color', prop: 'color', label: '标签颜色', span: 12 },
          { type: 'icon-selector', prop: 'icon', label: '标签图标', span: 24 },
        ]
      } else {
        // 新增模式：可以输入名字、颜色和图标
        return [
          { type: 'input', prop: 'name', label: '标签名字', span: 12 },
          { type: 'color', prop: 'color', label: '标签颜色', span: 12 },
          { type: 'icon-selector', prop: 'icon', label: '标签图标', span: 24 },
        ]
      }
    })

    const closeDialog = () => {
      visible.value = false
      isEdit.value = false
    }

    const updateData = async (param: TagSaveParam) => {
      // 转换颜色格式为标准的#FFFFFF格式
      if (param.color) {
        param.color = normalizeColor(param.color) || param.color
      }

      if (isEdit.value) {
        // 编辑模式：使用统一的update接口
        const updateParam: { id: string; color?: string; icon?: string } = {
          id: rowData.value.id,
        }

        // 只有当值发生变化时才传递参数
        if (param.color && param.color !== rowData.value.color) {
          updateParam.color = param.color
        }

        if (param.icon !== undefined && param.icon !== rowData.value.icon) {
          updateParam.icon = param.icon
        }

        if (updateParam.color !== undefined || updateParam.icon !== undefined) {
          await update(updateParam)
          ElMessage.success('标签更新成功')
        } else {
          ElMessage.info('没有需要更新的内容')
        }
      } else {
        // 新增模式：创建新标签
        await save(param)
        ElMessage.success('标签创建成功')
      }
      closeDialog()
      await getData()
    }

    return {
      visible,
      isEdit,
      rowData,
      editColumns,
      closeDialog,
      updateData,
    }
  }
</script>

<template>
  <div>
    <!--  搜索栏  -->
    <TableSearch :query="param" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <!--表格-->
      <TableCustom
        :columns="columns"
        :table-data="tableData"
        :total="total"
        :current-page="param.pageNum"
        :page-size="param.pageSize"
        :change-page="changePage"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        </template>
        <template #icon="{ row }">
          <div class="icon-display">
            <span class="icon-emoji">{{ row.icon || '🏷️' }}</span>
          </div>
        </template>
        <template #color="{ row }">
          <div v-if="row.color" class="color-display">
            <span class="color-box" :style="{ backgroundColor: row.color }"></span>
            <span class="color-text">{{ row.color }}</span>
          </div>
          <span v-else class="text-gray-400">未设置</span>
        </template>
        <template #operator="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </TableCustom>
    </div>

    <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑标签' : '新增标签'"
      width="700px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <TableEdit
        :form-data="rowData"
        label-width="100px"
        :span="12"
        :columns="editColumns"
        :edit="isEdit"
        :update="updateData"
      >
        <template #color="{ row }">
          <el-color-picker
            v-model="row.color"
            :predefine="colorPresets"
            show-alpha
            @active-change="
              (color: string | null) => {
                if (color) row.color = color
              }
            "
          />
        </template>
        <template #icon-selector="{ row }">
          <div class="icon-selector-container">
            <!-- 当前选中的图标显示 -->
            <div class="current-icon-display">
              <span class="current-icon">{{ row.icon || '🏷️' }}</span>
              <span class="current-icon-text">{{ row.icon ? '已选择' : '默认图标' }}</span>
            </div>

            <!-- 图标选择面板 -->
            <div class="icon-categories">
              <div v-for="category in iconCategories" :key="category.name" class="icon-category">
                <h4 class="category-title">{{ category.name }}</h4>
                <div class="category-icons">
                  <button
                    v-for="icon in category.icons"
                    :key="icon"
                    type="button"
                    class="icon-option"
                    :class="{ active: row.icon === icon }"
                    :title="icon"
                    @click.prevent="row.icon = icon"
                  >
                    {{ icon }}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </template>
      </TableEdit>
    </el-dialog>
  </div>
</template>

<style scoped>
  .color-display {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .color-box {
    display: inline-block;
    width: 20px;
    height: 20px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
  }

  .color-text {
    font-size: 12px;
    color: #606266;
  }

  .icon-display {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .icon-emoji {
    font-size: 18px;
  }

  .icon-selector-container {
    width: 100%;
    overflow: hidden;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background: #fafafa;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .current-icon-display {
    display: flex;
    align-items: center;
    gap: 14px;
    padding: 14px 18px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 0;
  }

  .current-icon {
    font-size: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 44px;
    height: 44px;
    background: white;
    border-radius: 50%;
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.12);
    border: 2px solid #e9ecef;
  }

  .current-icon-text {
    font-size: 14px;
    color: #495057;
    font-weight: 600;
  }

  .icon-categories {
    max-height: 360px;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 16px 20px;

    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f8f9fa;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;
      transition: background 0.3s ease;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #a8a8a8;
    }

    /* Firefox滚动条样式 */
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f8f9fa;
  }

  .icon-category {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 8px;
    }
  }

  .category-title {
    font-size: 13px;
    color: #343a40;
    margin: 0 0 12px 0;
    padding: 8px 14px;
    background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
    border-radius: 6px;
    font-weight: 700;
    border-left: 4px solid #6c757d;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  }

  .category-icons {
    display: grid;
    grid-template-columns: repeat(10, 1fr);
    gap: 10px;
    padding: 4px;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
  }

  .icon-option {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    background: white;
    border: 2px solid #e9ecef;
    border-radius: 8px;
    cursor: pointer;
    font-size: 18px;
    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    flex-shrink: 0;
    justify-self: center;
  }

  .icon-option:hover {
    border-color: #409eff;
    background: #ecf5ff;
    transform: translateY(-2px) scale(1.08);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.25);
    z-index: 2;
  }

  .icon-option.active {
    border-color: #409eff;
    background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
    color: white;
    transform: translateY(-2px) scale(1.08);
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
    z-index: 3;
  }

  .icon-option.active::after {
    content: '✓';
    position: absolute;
    bottom: -3px;
    right: -3px;
    width: 14px;
    height: 14px;
    background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
    color: white;
    border-radius: 50%;
    font-size: 9px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    border: 2px solid white;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  }
</style>
